# !/usr/bin/python
# _*_ coding: utf-8 _*_
# @Time : 2021/5/25 10:41 上午
# @Author : liujun
# @File : base.py
# @desc : 基础的Model Base类
from typing import Any
from sqlalchemy.ext.declarative import as_declarative, declared_attr
from sqlalchemy import inspect

from utils import IdWorker


@as_declarative()
class Base:
    id: Any
    __name__: str

    # auto generate table name
    @declared_attr
    def __tablename__(self) -> str:
        import re
        # 如果没有指定__tablename__  则默认使用model类名转换表名字
        name_list = re.findall(r"[A-Z][a-z\d]*", self.__name__)
        # 表明格式替换成_格式 如 SysUser 替换成 sys_user
        return "_".join(name_list).lower()

    def as_dict(self) -> dict:
        return {c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs}

    # 根据雪花算法生成id
    def get_id(self) -> int:
        worker = IdWorker(1, 1, 0)
        return worker.get_id()
